const config = require('../../utils/config.js')
const api = require('../../utils/api.js');
const util = require('../../utils/utils.js');
const regeneratorRuntime = require('../../utils/runtime.js');
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    userInfo: {},
    showLogin: false,
    isAuthor: 2,
    showRedDot: '',
    isShowPhoneModal: false,
    phoneNumber: '',
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: async function (options) {
    let that = this;
    app.checkUserInfo(function (userInfo, isLogin) {
      if (!isLogin) {
        that.setData({
          showLogin: true
        })
      } else {
        console.info('userInfo -> ',userInfo);
        that.setData({
          userInfo: userInfo
        })
      }
    });

    //this.handleRedDot()

    await that.checkAuthor()
  },

  onShow: function(e) {
    this.handleRedDot()
  },

  handleRedDot: function() {
    let showRedDot = wx.getStorageSync('showRedDot');
    console.info('showRedDot -> ', showRedDot)

    this.setData({
      showRedDot: showRedDot
    });
  },

  hidePhoneModal: function (e) {
    this.setData({
      isShowPhoneModal: false
    })
  },

  showPhoneModal: function (e) {
    this.setData({
      isShowPhoneModal: true
    })
  },

  savePhone: function(e) {
    let p = this.data.phoneNumber
    if (p == "") {
      wx.showToast({
        title: '手机号不能为空',
        icon: 'none',
        duration: 1500
      })
      return;
    }
    let user = {
      _id: wx.getStorageSync('openId'),
      phoneNumber: p,
      detail: this.data.userInfo,
      createTime: util.tsFormatTime(Date.now()),
      updateTime: util.tsFormatTime(Date.now())
    }
    let result = api.saveUser(user)
    console.info('saveUser result ->', result)

    this.checkUser(p)

    this.hidePhoneModal()
  },

  checkUser: function(phone) {
    let that = this
    api.determineAuthor(phone, function (res) {
      console.log('checkUser by phone result ->', res)
      if (res.data != undefined && res.data.length > 0) {
        api.updateAuthorOpenIdAndAvatar(res.data[0]._id, app.globalData.userInfo.avatarUrl)
        wx.removeStorageSync('isAuthor')
        that.checkAuthor()
      }
    })
  },

  onPhoneChange: function(e) {
    console.info('phone -> ', e.detail.value);
    this.setData({
      phoneNumber: e.detail.value
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    
  },
  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },

  /**
   * 返回
   */
  navigateBack: function (e) {
    wx.switchTab({
      url: '../index/index'
    })
  },

  getPhoneNumber(e) {
    console.log(e.detail.errMsg)
    console.log(e.detail.iv)
    console.log(e.detail.encryptedData)
  },

  /**
   * 获取用户头像
   * @param {} e 
   */
  getUserInfo: function (e) {
    console.info('userInfo -> ', e);
    if (e.detail.userInfo) {
      app.globalData.userInfo = e.detail.userInfo
      this.setData({
        showLogin: !this.data.showLogin,
        userInfo: e.detail.userInfo
      });
    } else {
      wx.switchTab({
        url: '../index/index'
      })
    }
  },
  /**
   * 展示打赏二维码
   * @param {} e 
   */
  showQrcode: async function (e) {
    wx.previewImage({
      urls: [config.moneyUrl],
      current: config.moneyUrl
    })
  },
  /**
   * 展示微信二维码
   * @param {*} e 
   */
  showWechatCode: async function (e) {
    wx.previewImage({
      urls: [config.wechatUrl],
      current: config.wechatUrl
    })
  },
  /**
   * 跳转我的收藏
   * @param {*} e 
   */
  bindCollect: async function (e) {
    wx.navigateTo({
      url: '../mine/collection/collection?type=1'
    })
  },
  /**
   * 跳转我的点赞 
   * @param {*} e 
   */
  bindZan: async function (e) {
    wx.navigateTo({
      url: '../mine/collection/collection?type=2'
    })
  },

  /**
   * 后台设置
   * @param {} e 
   */
  showAdmin: async function (e) {
    wx.navigateTo({
      url: '../admin/index'
    })
  },

  /**
   * 历史版本
   * @param {} e 
   */
  showRelease: async function (e) {
    wx.navigateTo({
      url: '../mine/release/release'
    })
  },

  /**
   * 我的消息
   * @param {*} e 
   */
  bindNotice: async function (e) {
    wx.navigateTo({
      url: '../mine/notice/notice'
    })
  },

  /**
   * 验证是否是管理员
   */
  checkAuthor: async function (e) {
    let that = this;
    const value = wx.getStorageSync('isAuthor')
    if (value != undefined && value != '') {
      console.info('storage isAuthor -> ', value)
      this.setData({
        isAuthor: value
      })
    }
    else {
      const openId = wx.getStorageSync('openId')
      if (openId != undefined && openId != '') {
        let author = await api.getAuthorByOpenId(openId)
        console.log('get author ->', author)
        if (author != null) {
          wx.setStorageSync('isAuthor', author.role)
          that.setData({
            isAuthor: author.role,
            phoneNumber: author._id,
          })
        } else {
          wx.setStorageSync('isAuthor', 2)
          that.setData({
            isAuthor: 2
          })
        }
      } 
    }
  }
})

